package com.oedtech.esl.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功handler
 * @Author QiuLongYu
 * @Date 2019/4/3
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final static Logger LOGGER= LoggerFactory.getLogger(LoginSuccessHandler.class);
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        LOGGER.info("用户[{}]登陆管理后台",authentication.getName());
        String  redirectUrl = "/"; //缺省的登陆成功页面
        SavedRequest savedRequest = (SavedRequest) httpServletRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
        if(savedRequest != null) {
            redirectUrl =   savedRequest.getRedirectUrl();
            httpServletRequest.getSession().removeAttribute("SPRING_SECURITY_SAVED_REQUEST");
        }
        httpServletResponse.sendRedirect(redirectUrl);
//        httpServletResponse.setContentType("application/json;charset=UTF-8");
//        JsonResult jsonResult=new JsonResult("success",redirectUrl);
//        httpServletResponse.getWriter().write(JSONObject.toJSONString(jsonResult));
    }
}
